package com.ym.manager.admin.user;

import com.alibaba.fastjson.JSONObject;
import com.ym.datasource.DataSourceContextHolder;
import com.ym.datasource.DataSourceType;
import com.ym.datasource.redis.JedisClient;
import com.ym.manager.admin.group.GroupInfo;
import com.ym.manager.admin.group.GroupService;
import com.ym.manager.admin.user.model.*;
import com.ym.manager.sys.model.AdminUser;
import com.ym.manager.yinsheng.util.RequestData;
import com.ym.manager.yinsheng.util.ServiceEnum;
import com.ym.manager.yinsheng.util.YinShengClient;
import com.ym.utils.*;
import com.ym.web.bind.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: dhf
 * @ClassName: AppUserController
 * @Date: 2022/8/22 9:48
 * @Description: app用户
 * @Version: 1.0
 */
@RequestMapping("/app/user")
@Controller
public class AppUserController {
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private GroupService groupService;
    private final TransactionTemplate transactionTemplate;
    public AppUserController(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @RequestMapping("/index")
    public String index(Model model){
        return "user/list";
    }

    @ResponseBody
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "0") int start,
                       @RequestParam(defaultValue = "10")int length,
                       @RequestParam(defaultValue = "")String mobile,
                       @RequestParam(defaultValue = "")String nickName,
                       @RequestParam(defaultValue = "0")long id,
                       @RequestParam(defaultValue = "-1") int status,
                       @RequestParam(defaultValue = "") String alias,
                       @RequestParam(defaultValue = "")String alipayUid,
                       @RequestParam(defaultValue = "")String alipayName,
                       @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        try {
            String aliBlackId = appUserService.aliBlackId();
            List<String> aliBlackIdList = null;
            if(StringHandler.isNotEmpty(aliBlackId)){
                aliBlackIdList = Arrays.asList(aliBlackId.split(","));
            }
            if(StringHandler.isNotEmpty(alias)){
                id = McodeHandler.from32Radix(alias);
            }
            Pages<UserInfo> pages = appUserService.getList(start,length,nickName,mobile,id,status,aliBlackIdList,alipayUid,alipayName);
            //查询数据
            result.put("data",pages.getList());
            result.put("count",pages.getTotal());
            result.put("recordsTotal",pages.getTotal());
            result.put("recordsFiltered",pages.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            result.put("code",-1000);
            result.put("msg","系统异常");
        }
        return ResultUtil.toJSON(result);
    }

    @RequestMapping("/query")
    public String query(Model model){
        return "user/queryList";
    }
    @RequestMapping("/group/apply/index")
    public String groupApplyIndex(Model model){
        return "user/groupApplyList";
    }

    @ResponseBody
    @RequestMapping("/group/apply/list")
    public String groupApplyList(@RequestParam(defaultValue = "0") int start,
                                 @RequestParam(defaultValue = "10")int length,
                       @RequestParam(defaultValue = "")String mobile,
                       @RequestParam(defaultValue = "0")int id,
                       @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        try {
            Pages<UserInfo> pages = appUserService.groupApplyList(start,length,mobile,id);
            //查询数据
            result.put("data",pages.getList());
            result.put("count",pages.getTotal());
            result.put("recordsTotal",pages.getTotal());
            result.put("recordsFiltered",pages.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            result.put("code",-1000);
            result.put("msg","系统异常");
        }
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/sync/money")
    public String syncMoney(@RequestParam(defaultValue = "0")long id,@CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(id<=0){
            result.put("code",-1000);
            result.put("msg","用户id为空");
            return ResultUtil.toJSON(result);
        }
        Map<String,Object> userAccountInfo = appUserService.userAccountInfo(id);
        if(StringHandler.isEmpty(userAccountInfo)){
            result.put("code",-1000);
            result.put("msg","该用户未有资金账户");
            return ResultUtil.toJSON(result);
        }
        Map<String,Object> merchantInfo = appUserService.merchantInfo(id);
        if(StringHandler.isEmpty(merchantInfo)){
            result.put("code",-1000);
            result.put("msg","该用户还未有商户信息");
            return ResultUtil.toJSON(result);
        }
        boolean isTrue = true;
        String remark = "操作成功";
        try {
            String merchantNo = StringHandler.getString(merchantInfo.get("merchantNo"));
            if(StringHandler.isEmpty(merchantNo)){
                result.put("code",-1000);
                result.put("msg","该用户商户信息为空");
                return ResultUtil.toJSON(result);
            }
            // 组装业务参数
            Map<String,Object> requestMap = new HashMap<>();
            requestMap.put("merchantNo", merchantNo);
            RequestData requestData = new RequestData(requestMap);
            YinShengClient yinShengClient = new YinShengClient(ServiceEnum.QUERY_AMOUNT);
            String callback = yinShengClient.requestStrApi(requestData);
            if(StringHandler.isEmpty(callback)){
                result.put("code",-1000);
                result.put("msg","账户余额查询失败");
            }
            Map<String, Object> obj = JsonUtil.jsonToBean(callback, Map.class);
            String cashAmount = "";
            if (!obj.get("code").equals("SYS000")) {
                remark = "账户余额查询失败:" + StringHandler.getString(obj.get("msg"));
                Logger.error(remark);
                isTrue = false;
            } else {
                if (StringHandler.isNotEmpty(StringHandler.getString(obj.get("bizResponseJson")))) {
                    Map<String, Object> bizResponseJson = JsonUtil.jsonToBean(JsonUtil.toJson(obj.get("bizResponseJson")), Map.class);
                    if (bizResponseJson.get("subCode").equals("COM000")) {
                        List<Map<String, Object>> accountList = JsonUtil.jsonToBean(JsonUtil.toJson(bizResponseJson.get("accountList")), List.class);
                        if(StringHandler.isNotEmpty(accountList)){
                            for (Map<String, Object> accountMap: accountList){
                                if("01".equals(StringHandler.getString(accountMap.get("accountType")))){
                                    cashAmount = StringHandler.getString(accountMap.get("cashAmount"));
                                }
                            }
                        }
                    }  else {
                        remark = "账户余额查询失败:" + StringHandler.getString(bizResponseJson.get("subMsg"));
                        Logger.error(remark);
                        isTrue = false;
                    }
                } else {
                    remark = "账户余额查询失败:返回信息为空";
                    Logger.error(remark);
                    isTrue = false;
                }
            }
            if(isTrue){
                if(StringHandler.yuanToFen(cashAmount)!=StringHandler.getLong(userAccountInfo.get("balance"))){
                    long  finalCashAmount = StringHandler.yuanToFen(cashAmount);
                    DataSourceContextHolder.setDataSourceType(DataSourceType.YS_IM.getSource());
                    transactionTemplate.execute(e->{
                        int i = appUserService.userAccountUpdate(id,finalCashAmount,DateHandler.getDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        if(i<=0){
                            throw new RuntimeException("修改账户信息错误");
                        }
                        i = appUserService.userAccountSyncRecordInsert(id,StringHandler.getLong(userAccountInfo.get("balance")),finalCashAmount,DateHandler.getLongFormatDate(),user.getId(),user.getUsername());
                        if(i<=0){
                            throw new RuntimeException("添加同步账户金额记录错误");
                        }
                        return 1;
                    });
                    DataSourceContextHolder.clearDataSourceType();
                    remark = "同步成功";
                }else{
                    remark = "同步成功，账户金额相同未修改信息";
                }
                result.put("msg",remark);
            }else{
                result.put("code",-1000);
                result.put("msg",remark);
            }
            result.put("cashAmount",cashAmount);
            result.put("balance",StringHandler.fenToYuan(userAccountInfo.get("balance")+""));
        }catch (Exception e){
            e.printStackTrace();
            result.put("code",-1000);
            result.put("msg","系统异常");
        }
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/group/apply/status")
    public String groupApplyStatus(long id,int status){
        Map<String,Object> result = ResultUtil.result();
        try {
            appUserService.groupApplyStatus(id,status);
        }catch (Exception e){
            e.printStackTrace();
            result.put("code",-1000);
            result.put("msg","系统异常");
        }
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/update/status")
    public String updateStatus(long uid,int status){
        Map<String,Object> result = ResultUtil.result();
        try {
            if(status==2){
                String data = HttpUtils.post("http://172.24.194.56:8082/manager/user/freeze", MapHandler.initMap("id",uid+"","status",status+""));
                JSONObject jsonObject = JSONObject.parseObject(data);
                if(!jsonObject.getString("code").equals("0")){
                    throw new RuntimeException(jsonObject.getString("msg"));
                }
            }else{
                int i = appUserService.updateStatus(uid,status);
            }
            jedisClient.del("user:info:"+uid);
        }catch (Exception e){
            e.printStackTrace();
            result.put("code",-1000);
            result.put("msg","系统异常");
        }
        return ResultUtil.toJSON(result);
    }

    /**
     * @author 但何非
     * @dateTime 2022/11/16 13:31
     * @params
     * @param uid:
     * @param status: 1 关闭拉黑 2 开启拉黑
     * @return
     * @return java.lang.String
     * @Description:用户提现拉黑
     */
    @ResponseBody
    @RequestMapping("/withdraw/black/status")
    public String userWithdrawBlackStatus(long uid,int status){
        Map<String,Object> result = ResultUtil.result();
        DataSourceContextHolder.setDataSourceType("ysIm");
        transactionTemplate.execute(e->{
            if(status == 1){
                //删除拉黑
                appUserService.userWithdrawBlackDel(uid);
                //修改提现记录状态
                appUserService.withdrawRecordStatus(uid,1);
            }
            if(status==2){
                // 添加拉黑
                appUserService.userWithdrawBlackInsert(uid,DateHandler.getLongFormatDate());
                // 修改提现记录状态
                appUserService.withdrawRecordStatus(uid,7);
            }
            return 1;
        });
        DataSourceContextHolder.clearDataSourceType();
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("/account/flow/index")
    public String withdrawRecordList(Model model,@RequestParam(defaultValue = "0") long uid){
        model.addAttribute("uid",uid);
        model.addAttribute("typeList",AccountFlowType.gettypeList());
        return "user/accountFlowList";
    }
    @ResponseBody
    @RequestMapping("/account/flow/list")
    public String accountFlowList(@RequestParam(defaultValue = "0") int start,
                       @RequestParam(defaultValue = "10")int length,
                       @RequestParam(defaultValue = "0")long uid,
                       @RequestParam(defaultValue = "")String type,
                                  @RequestParam(defaultValue = "0")int payChannel,
                       @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(uid>0) {
            try {
                Pages<AccountFlowVo> pages = appUserService.accountFlowList(start, length, uid,type,payChannel);
                //查询数据
                result.put("data", pages.getList());
                result.put("count", pages.getTotal());
                result.put("recordsTotal", pages.getTotal());
                result.put("recordsFiltered", pages.getTotal());
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", -1000);
                result.put("msg", "系统异常");
            }
        }else{
            result.put("count", 0);
            result.put("recordsTotal", 0);
            result.put("recordsFiltered", 0);
        }
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("/red/index")
    public String redList(Model model,@RequestParam(defaultValue = "0") long uid){
        model.addAttribute("uid",uid);
        return "user/redList";
    }
    @ResponseBody
    @RequestMapping("/red/list")
    public String redList(@RequestParam(defaultValue = "0") int start,
                                  @RequestParam(defaultValue = "10")int length,
                                  @RequestParam(defaultValue = "0")long uid,
                                  @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(uid>0) {
            try {
                Pages<RedVo> pages = appUserService.redList(start, length, uid);
                //查询数据
                result.put("data", pages.getList());
                result.put("count", pages.getTotal());
                result.put("recordsTotal", pages.getTotal());
                result.put("recordsFiltered", pages.getTotal());
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", -1000);
                result.put("msg", "系统异常");
            }
        }else{
            result.put("count", 0);
            result.put("recordsTotal", 0);
            result.put("recordsFiltered", 0);
        }
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/red/update")
    public String redUpdate(
                          @RequestParam(defaultValue = "0")long redId,
                          @RequestParam(defaultValue = "0")long uid,
                          @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(redId>0 &&uid>0) {
            try {
                int redCount = appUserService.redCount(redId,uid);
                if(redCount>0){
                    appUserService.redUpdate(redId, uid);
                }else{
                    result.put("code", -1000);
                    result.put("msg", "当前红包不能修改");
                }
                //查询数据
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", -1000);
                result.put("msg", "系统异常");
            }
        }else{
            result.put("code", -1000);
            result.put("msg", "红包信息错误");
        }
        return ResultUtil.toJSON(result);
    }

    @RequestMapping("/transfer/index")
    public String transferList(Model model,@RequestParam(defaultValue = "0") long uid){
        model.addAttribute("uid",uid);
        return "user/transferList";
    }
    @ResponseBody
    @RequestMapping("/transfer/list")
    public String transferList(@RequestParam(defaultValue = "0") int start,
                          @RequestParam(defaultValue = "10")int length,
                          @RequestParam(defaultValue = "0")long uid,
                          @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(uid>0) {
            try {
                Pages<TransferVo> pages = appUserService.transferList(start, length, uid);
                //查询数据
                result.put("data", pages.getList());
                result.put("count", pages.getTotal());
                result.put("recordsTotal", pages.getTotal());
                result.put("recordsFiltered", pages.getTotal());
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", -1000);
                result.put("msg", "系统异常");
            }
        }else{
            result.put("count", 0);
            result.put("recordsTotal", 0);
            result.put("recordsFiltered", 0);
        }
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/transfer/update")
    public String transferUpdate(
                                @RequestParam(defaultValue = "0")long transferId,
                               @RequestParam(defaultValue = "0")long uid,
                               @CurrentUser AdminUser user){
        Map<String,Object> result = ResultUtil.result();
        if(uid>0) {
            try {
                int redCount = appUserService.transferCount(transferId,uid);
                if(redCount>0){
                    appUserService.transferUpdate(transferId, uid);
                }else{
                    result.put("code", -1000);
                    result.put("msg", "转账不能修改");
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", -1000);
                result.put("msg", "系统异常");
            }
        }else{
            result.put("code", -1000);
            result.put("msg", "转账信息错误");
        }
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("/check/user/amount/index")
    public String checkUserAmountIndex(Model model,@RequestParam(defaultValue = "0") long uid){
        model.addAttribute("uid",uid);
        return "user/checkUserAmountList";
    }
    @ResponseBody
    @RequestMapping("/check/user/amount/list")
    public String checkUserAmountList(@RequestParam(defaultValue = "0") int start,
                                      @RequestParam(defaultValue = "10")int length,
                                      @RequestParam(defaultValue = "0")int beginTime,
                                      @RequestParam(defaultValue = "0")int endTime,
                                      @RequestParam(defaultValue = "1")int type){
        Map<String,Object> result = ResultUtil.result();
        Pages<Map<String, Object>> pages = appUserService.checkUserAmountList(start,length,beginTime,endTime,type);
        result.put("data", pages.getList());
        result.put("count", pages.getTotal());
        result.put("recordsTotal", pages.getTotal());
        result.put("recordsFiltered", pages.getTotal());
        return ResultUtil.toJSON(result);
    }

    @RequestMapping("/add/index")
    public String addIndex(){
        return "user/add";
    }
    @ResponseBody
    @RequestMapping("/add/user")
    public String addUser(String phone,String password){
        Map<String,Object> result = ResultUtil.result();
        appUserService.addUser(phone,password);
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/ali/black")
    public String aliBlack(long userId ,String alipayUid){
        String aliBlackId = appUserService.aliBlackId();
        if(!StringHandler.isEmpty(aliBlackId)){
            aliBlackId = aliBlackId+","+alipayUid;
        }else{
            aliBlackId = alipayUid;
        }
        Map<String,Object> result = ResultUtil.result();
        appUserService.aliBlack(aliBlackId);
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/ali/black/un")
    public String aliBlackUn(long userId ,String alipayUid){
        Map<String,Object> result = ResultUtil.result();
        String aliBlackId = appUserService.aliBlackId();
        if(StringHandler.isEmpty(aliBlackId)){
            return ResultUtil.toJSON(result);
        }
        List<String> aliBlackIdList = Arrays.asList(aliBlackId.split(","));
        String blackId = "";
        for (String aliId:aliBlackIdList) {
            if(!aliId.equals(alipayUid)){
                if(StringHandler.isEmpty(blackId)){
                    blackId = aliId;
                }else{
                    blackId = blackId+","+aliId;
                }
            }
        }
        appUserService.aliBlack(blackId);
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/redisInfo")
    public String redisInfoUid(String phone){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isEmpty(phone)){
            result.put("code", -1000);
            result.put("msg", "请输入电话号码");
            return ResultUtil.toJSON(result);
        }
        UserInfo userInfo = appUserService.getUserInfoByPhone(phone);
        if(StringHandler.isEmpty(userInfo)) {
            jedisClient.del("user:phone:" + phone);
            result.put("code", -1000);
            result.put("msg", "用户信息不存在,已删除电话号的缓存");
        }else{
            jedisClient.del("user:phone:" + userInfo.phone);

            jedisClient.del(String.format("user:info:%s", userInfo.id));

            jedisClient.del(String.format("user:unionId:%s", userInfo.unionId));
        }
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/user/ip/black")
    public String userIpBlack(String userIp){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isEmpty(userIp)){
            result.put("code", -1000);
            result.put("msg", "请输入IP");
            return ResultUtil.toJSON(result);
        }
        String blackIp = appUserService.configValue("sys.black.ips");
        if(!blackIp.contains(userIp)) {
            appUserService.addBlackIp(","+userIp);
        }else{
            result.put("code", -1000);
            result.put("msg", "当前ip已拉黑");
            return ResultUtil.toJSON(result);
        }
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/user/ip/black/un")
    public String userIpBlackUn(String userIp){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isEmpty(userIp)){
            result.put("code", -1000);
            result.put("msg", "请输入IP");
            return ResultUtil.toJSON(result);
        }
        String blackIp = appUserService.configValue("sys.black.ips");
        if(!blackIp.contains(userIp)) {
            result.put("code", -1000);
            result.put("msg", "当前ip已解除");
            return ResultUtil.toJSON(result);
        }else{
            List<String> listIp = Arrays.asList(blackIp.split(","));
            List<String> list = listIp.stream().filter(o->!o.equals(userIp)).collect(Collectors.toList());
            String ip = list.stream().collect(Collectors.joining(","));
            appUserService.updateBlackIp(ip);
        }
        return ResultUtil.toJSON(result);
    }

    @RequestMapping("/user/operation/index")
    public String operationIndex(){
        return "user/operation";
    }


    /**
     * @作者: dhf
     * @名称:删除用户所有数据
     * @param userId
     * @时间: 2023/3/1 20:39
     * @备注:
     * @返回值: java.lang.String
     */
    public String delUserData(long userId){
        Map<String,Object> result = ResultUtil.result();
        appUserService.delUserData(userId);
        //清除缓存
        //群信息
        return ResultUtil.toJSON(result);
    }

    /**
     * @作者: dhf
     * @名称:查询用户配置信息
     * @param userId
     * @时间: 2023/3/1 20:48
     * @备注:
     * @返回值: java.lang.String
     */
    @ResponseBody
    @RequestMapping("/user/config")
    public String userConfig(long userId){
        Map<String,Object> result = ResultUtil.result();
        UserConfig userConfig = appUserService.userConfig(userId);
        result.put("data",userConfig);
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/friends/copy")
    public String friendsCopy(long userId,int type){
        Map<String,Object> result = ResultUtil.result();
        appUserService.friendsCopy(userId,type);
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("/user/bank/index")
    public String bankIndex(Model model,@RequestParam(defaultValue = "0")long id){
        model.addAttribute("id", id);
        return "/user/bankIndex";
    }
    @ResponseBody
    @RequestMapping("/user/bank/list")
    public String bankList( @RequestParam(defaultValue = "0") int start,
                            @RequestParam(defaultValue = "10")int length,
                            @RequestParam(defaultValue = "0")long id,
                            @RequestParam(defaultValue = "") String alias,
                            @RequestParam(defaultValue = "") String card_no){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isNotEmpty(alias)){
            id = McodeHandler.from32Radix(alias);
        }
        Pages<Map<String,Object>> pages = appUserService.bankList(start,length,id,card_no);
        result.put("data",pages.getList());
        result.put("count",pages.getTotal());
        result.put("recordsTotal",pages.getTotal());
        result.put("recordsFiltered",pages.getTotal());
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/group/black/user")
    public String groupBlackUser(String groupUserPhone,long groupId){
        Map<String,Object> result = ResultUtil.result();
        UserInfo userInfo = appUserService.getUserInfoByPhone(groupUserPhone);
        if(StringHandler.isEmpty(userInfo)){
            result.put("code", -1000);
            result.put("msg", "当前人员信息为空");
            return ResultUtil.toJSON(result);
        }
        GroupInfo groupInfo = groupService.groupInfo(groupId);
        if(StringHandler.isEmpty(groupInfo)){
            result.put("code", -1000);
            result.put("msg", "群信息为空");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.is_freeze){
            result.put("code", -1000);
            result.put("msg", "该群已被封禁");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.is_freeze){
            result.put("code", -1000);
            result.put("msg", "该群已被封禁");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.status!=1){
            result.put("code", -1000);
            result.put("msg", "该群已解散");
            return ResultUtil.toJSON(result);
        }
        if(appUserService.groupBlackUserCount(groupId,StringHandler.getLong(groupInfo.user_id),userInfo.id)>0){
            result.put("code", -1000);
            result.put("msg", "该用户已被群拉黑");
            return ResultUtil.toJSON(result);
        }
        appUserService.groupBlackUser(groupId,StringHandler.getLong(groupInfo.user_id),userInfo.id);
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/group/black/user/un")
    public String groupBlackUserUn(String groupUserPhone,long groupId){
        Map<String,Object> result = ResultUtil.result();
        UserInfo userInfo = appUserService.getUserInfoByPhone(groupUserPhone);
        if(StringHandler.isEmpty(userInfo)){
            result.put("code", -1000);
            result.put("msg", "当前人员信息为空");
            return ResultUtil.toJSON(result);
        }
        GroupInfo groupInfo = groupService.groupInfo(groupId);
        if(StringHandler.isEmpty(groupInfo)){
            result.put("code", -1000);
            result.put("msg", "群信息为空");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.is_freeze){
            result.put("code", -1000);
            result.put("msg", "该群已被封禁");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.is_freeze){
            result.put("code", -1000);
            result.put("msg", "该群已被封禁");
            return ResultUtil.toJSON(result);
        }
        if(groupInfo.status!=1){
            result.put("code", -1000);
            result.put("msg", "该群已解散");
            return ResultUtil.toJSON(result);
        }
        appUserService.groupBlackUserUn(groupId,StringHandler.getLong(groupInfo.user_id),userInfo.id);
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/red/add/redis")
    public String redAddRedis(long redId){
        Map<String,Object> result = ResultUtil.result();
        Map<String,Object> red = appUserService.getRedMapInfo(redId);
        if(StringHandler.isEmpty(red)){
            result.put("code", -1000);
            result.put("msg", "当前佣金信息为空");
            return ResultUtil.toJSON(result);
        }
        int redDealCount = appUserService.getRedDealCount(redId);
        int redNum = StringHandler.getInt(red.get("size"))-redDealCount;
        int redAmount = StringHandler.getInt(red.get("amount"));
        if(redNum>0) {
            List<Integer> redPackageList = new ArrayList<>();
            for (int i = 0; i < redNum; i++) {
                redPackageList.add(redAmount);
            }
            // 剩余红包缓存
            String redKey = "redis-red-groupnormal:prefix:" + redId;
            jedisClient.setList(redKey, redPackageList.stream().map(StringHandler::getString).collect(Collectors.toList()),0);

            String gradkey = "redis-red:prefix:" + redId;
            jedisClient.set(gradkey,StringHandler.getString(red.get("group_name")),60 * 60 * 23);
        }else{
            result.put("code", -1000);
            result.put("msg", "当前佣金已领取");
            return ResultUtil.toJSON(result);
        }
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/red/all/add/redis")
    public String redAllAddRedis(String endTime){
        Map<String,Object> result = ResultUtil.result();
        List<Map<String,Object>> list = appUserService.getRedList(endTime);
        if(StringHandler.isEmpty(list)){
            result.put("code", -1000);
            result.put("msg", "当前佣金信息为空");
            return ResultUtil.toJSON(result);
        }
        for(Map<String,Object> red:list) {
            if(StringHandler.getInt(red.get("size"))==1){
                long redId = StringHandler.getLong(red.get("id"));
                int redDealCount = appUserService.getRedDealCount(redId);
                int redNum = StringHandler.getInt(red.get("size")) - redDealCount;
                int redAmount = StringHandler.getInt(red.get("amount"));
                if (redNum > 0) {
                    List<Integer> redPackageList = new ArrayList<>();
                    for (int ii = 0; ii < redNum; ii++) {
                        redPackageList.add(redAmount);
                    }
                    // 剩余红包缓存
                    String redKey = "redis-red-groupnormal:prefix:" + redId;
                    jedisClient.setList(redKey, redPackageList.stream().map(StringHandler::getString).collect(Collectors.toList()), 0);

                    String gradkey = "redis-red:prefix:" + redId;
                    jedisClient.set(gradkey, StringHandler.isEmpty(StringHandler.getString(red.get("group_name")))?redId+"":StringHandler.getString(red.get("group_name")), 60 * 60 * 23);
                } else {
                    result.put("code", -1000);
                    result.put("msg", "当前佣金已领取");
                    return ResultUtil.toJSON(result);
                }
            }
        }
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/trans/all/add/redis")
    public String transAllAddRedis(String endTime){
        Map<String,Object> result = ResultUtil.result();
        List<Map<String,Object>> list = appUserService.getTransList(endTime);
        if(StringHandler.isEmpty(list)){
            result.put("code", -1000);
            result.put("msg", "当前佣金信息为空");
            return ResultUtil.toJSON(result);
        }
        for(Map<String,Object> red:list) {
            long redId = StringHandler.getLong(red.get("id"));
            long userId = StringHandler.getLong(red.get("user_id"));
            String list_user_id = StringHandler.getString(red.get("list_user_id"));
            int redAmount = StringHandler.getInt(red.get("amount"));
            String gradkey = "redis-transfer:prefix:" + redId;
            jedisClient.set(gradkey, StringHandler.isEmpty(StringHandler.getString(red.get("group_name")))?redId+"":StringHandler.getString(red.get("group_name")), 60 * 60 * 23);
            String redKey = "redis-transfer-single:prefix:" + redId + "-" + userId;
            jedisClient.del(redKey);
            String redKey1 = "redis-transfer-single:prefix:" + redId + "-" + list_user_id;
            jedisClient.set(redKey1, redAmount+"", 0);
        }
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("/friend/index")
    public String friendIndex(Model model,@RequestParam(defaultValue = "0")long id){
        model.addAttribute("id", id);
        return "/user/friendList";
    }
    @ResponseBody
    @RequestMapping("/friend/list")
    public String friendList( @RequestParam(defaultValue = "0") int start,
                            @RequestParam(defaultValue = "10")int length,
                            @RequestParam(defaultValue = "0")long uid,
                              @RequestParam(defaultValue = "1")int status,
                            @RequestParam(defaultValue = "") String alias){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isNotEmpty(alias)){
            uid = McodeHandler.from32Radix(alias);
        }
        Pages<UserFriendsInfo> pages = appUserService.friendList(start,length,uid,status);
        result.put("data",pages.getList());
        result.put("count",pages.getTotal());
        result.put("recordsTotal",pages.getTotal());
        result.put("recordsFiltered",pages.getTotal());
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/ali/un/bind")
    public String aliUnBind(@RequestParam(defaultValue = "0")long uid){
        Map<String,Object> result = ResultUtil.result();
        int i = appUserService.updateAliByUser(uid);
        if (i != 1) {
            result.put("code", 500);
            result.put("msg", "解绑失败");
            return ResultUtil.toJSON(result);
        }
        jedisClient.del(String.format("user:info:%s", uid));
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/ip/adds")
    public String ipadds(@RequestParam(defaultValue = "")String ip){
        Map<String,Object> result = ResultUtil.result();
        if(StringHandler.isEmpty(ip)){
            result.put("code", 500);
            result.put("msg", "IP不能为空");
            return ResultUtil.toJSON(result);
        }
        String adds = "";
        try {
            adds = HttpUtils.sendGet("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true");
            result.put("adds",JsonUtil.jsonToBean(adds,Map.class));
        }catch (Exception e){
            result.put("code", -1);
            result.put("msg", "获取失败");
            Logger.error("根据IP获取地址信息错误",e);
        }

        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/del/data")
    public String delData(@RequestParam(defaultValue = "0")long userId){
        Map<String,Object> result = ResultUtil.result();
        if(userId<=0){
            result.put("code", 500);
            result.put("msg", "用户id不能为空");
            return ResultUtil.toJSON(result);
        }
        try {
            appUserService.delData(userId);
        }catch (Exception e){
            result.put("code", -1);
            result.put("msg", "清除失败");
            Logger.error("用户id信息错误",e);
        }

        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/user/bank/del")
    public String bankDel( @RequestParam(defaultValue = "0")long id,
                           @RequestParam(defaultValue = "") long uid){
        Map<String,Object> result = ResultUtil.result();
        int i = appUserService.bankDel(id,uid);
        if (i != 1) {
            result.put("code", 500);
            result.put("msg", "删除银行卡失败");
            return ResultUtil.toJSON(result);
        }
        return ResultUtil.toJSON(result);
    }
    @ResponseBody
    @RequestMapping("/red/record/list")
    public String redRecordList( @RequestParam(defaultValue = "0")long redId){
        Map<String,Object> result = ResultUtil.result();
        if(redId<0){
            return ResultUtil.toJSON(result);
        }
        List<Map<String,Object>> list = appUserService.redRecordList(redId);
        list = list.stream().map(x->{
                    String money = StringHandler.fenToYuan(StringHandler.getString(x.get("amount")));
                    x.put("money",money);
                    return x;
                }).collect(Collectors.toList());
        result.put("list",list);
        return ResultUtil.toJSON(result);
    }

    @ResponseBody
    @RequestMapping("/refresh/user/friends")
    public String refreshUserFriends(String userId){
        Map<String,Object> result = ResultUtil.result();
        List<BaseUserFriendsPO> friendsList = appUserService.getFriendsListByUserId(userId);
        if (StringHandler.isNotEmpty(friendsList) && friendsList.size()>0) {
            //保存缓存
            Map<String, String> collect = friendsList
                    .stream()
                    .collect(Collectors.toMap(BaseUserFriendsPO::getFriendId, JsonUtil::toJson));
            jedisClient.setMap("user:friends:"+userId, collect,60 * 60 * 24 * 30);
            friendsList.forEach(o -> {
                o.setUserId(McodeHandler.to32Radix(Long.parseLong(o.getUserId())));
                o.setFriendId(McodeHandler.to32Radix(Long.parseLong(o.getFriendId())));
            });
        }
        return ResultUtil.toJSON(result);
    }
}
